package com.hjs.servlet.road;

import com.hjs.bean.*;
import com.hjs.mapper.RoadAuditMapper;
import com.hjs.mapper.RoadMapper;
import com.hjs.mapper.RoadTypeMapper;
import com.hjs.mapper.RoadwayMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author flamemaster
 * @date 2020/6/19
 **/
@Slf4j
@WebServlet("/road/update")
public class Update extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        RequestUtil requestUtil = new RequestUtil(request, response);
        switch (Integer.parseInt(request.getParameter("updateType"))) {
            case 1:
                updateRoadBase(requestUtil);
                break;
            case 2:
                updateRoadway(requestUtil);
                break;
            case 3:
                updateRoadType(requestUtil);
                break;
            case 4:
                updateMaintenanceLevel(requestUtil);
                break;
            case 5:
                updateAffiliatedFacility(requestUtil);
                break;
            case 6:
                updateDividerOneSide(requestUtil);
                break;
            case 7:
                updateSidewalkOneSide(requestUtil);
                break;
            case 8:
                updateAudit(requestUtil);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + Integer.parseInt(request.getParameter("addType")));
        }
    }



    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){

    }

    private void updateRoadBase(RequestUtil requestUtil) {
        Road road = new Road(requestUtil.getInt("roadID"), requestUtil.getString("roadName"),
                requestUtil.getString("roadDirection"), requestUtil.getString("startPoint"),
                requestUtil.getString("endPoint"), requestUtil.getString("designUnit"),
                requestUtil.getString("constructionUnit"), requestUtil.getInt("roadTypeID"),
                requestUtil.getString("roadLevel"), requestUtil.getDouble("designedSpeed"),
                requestUtil.getString("roadWidthRange"), requestUtil.getDouble("roadLength"),
                requestUtil.getDouble("roadArea"), requestUtil.getDouble("AADT"),
                requestUtil.getString("trafficLevel"), requestUtil.getString("township"),
                requestUtil.getString("managementClassification"), requestUtil.getString("managementUnit"),
                requestUtil.getString("maintenanceUnit"), requestUtil.getDate("constructionDate"),
                null, null);
        Mapper<RoadMapper> roadMapperMapper = new Mapper<>(RoadMapper.class);
        try {
            RoadMapper mapper = roadMapperMapper.getMapper();
            boolean result = mapper.updateOneRoad(road);
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        } finally {
            roadMapperMapper.closeSession();
        }
    }

    private void updateRoadway(RequestUtil requestUtil) {

        try (SqlSession sqlSession = Mapper.getSqlSession()) {
            Roadway roadway = new Roadway(requestUtil.getInt("roadwayID"), requestUtil.getInt("numberOfLanes"),
                    requestUtil.getString("trafficDirection"), requestUtil.getString("roadwayWidthRange"),
                    requestUtil.getString("leftNonRoadwayWidthRange"), requestUtil.getString("rightNonRoadwayWidthRange"),
                    requestUtil.getDouble("roadwayArea"), requestUtil.getInt("busLane"),
                    requestUtil.getInt("roadID"));
            RoadwayMapper mapper = sqlSession.getMapper(RoadwayMapper.class);
            boolean sqlResult = mapper.updateOneRoadway(roadway);
            requestUtil.responseWrite("{\"result\":" + "车行道-" + sqlResult + "}");
            if (sqlResult) {
                sqlResult = updateAll(requestUtil, mapper, roadway.getRoadwayID());
            }
            Mapper.SessionEnd(sqlResult, sqlSession);
            requestUtil.responseIsSuccess(sqlResult,"成功！");
        } catch (Exception e) {
            log.error(e.toString());
            requestUtil.responseFail("未知原因失败！");
        }
    }

    private boolean updateAll(RequestUtil requestUtil, RoadwayMapper mapper, Integer roadwayID) {
        String[] length = {"position", "type", "Length"};
        for (int i = 0; i < requestUtil.getInt("lengthNumber"); i++) {
            boolean sqlResult = mapper.updateOneTypeAndLength(new TypeAndLength(roadwayID,
                    requestUtil.getInt(length[0]+i),requestUtil.getString(length[1]+i),
                    requestUtil.getDouble(length[2]+i)));
            if (!sqlResult) {
                return false;
            }
        }
        String[] thick = {"thickposition", "thicktype", "thickness"};
        for (int i = 0; i < requestUtil.getInt("thickNumber"); i++) {
            boolean sqlResult = mapper.updateOneTypeAndThickness(new TypeAndThickness(roadwayID,
                    requestUtil.getInt(thick[0]+i),requestUtil.getString(thick[1]+i),
                    requestUtil.getDouble(thick[2]+i)));
            if (!sqlResult) {
                return false;
            }
        }
        return true;
    }


    private void updateRoadType(RequestUtil requestUtil) {
        RoadType roadType = new RoadType(requestUtil.getInt("roadTypeID"), requestUtil.getString("type"),
                requestUtil.getInt("maintenanceLevelID"));
        Mapper<RoadTypeMapper> roadTypeMapperMapper = new Mapper<>(RoadTypeMapper.class);
        try {
            RoadTypeMapper mapper = roadTypeMapperMapper.getMapper();
            boolean result = mapper.updateOneRoadType(roadType);
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        } finally {
            roadTypeMapperMapper.closeSession();
        }
    }

    private void updateMaintenanceLevel(RequestUtil requestUtil) {
        MaintenanceLevel maintenanceLevel = new MaintenanceLevel(requestUtil.getInt("maintenanceLevelID"),
                requestUtil.getString("maintenanceLevelName"));
        Mapper<RoadTypeMapper> roadTypeMapperMapper = new Mapper<>(RoadTypeMapper.class);
        log.info("asdasd");
        try {
            RoadTypeMapper mapper = roadTypeMapperMapper.getMapper();
            boolean result = mapper.updateOneMaintenanceLevel(maintenanceLevel);
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        } finally {
            roadTypeMapperMapper.closeSession();
        }
    }

    private void updateAffiliatedFacility(RequestUtil requestUtil) {
        AffiliatedFacility affiliatedFacility = new AffiliatedFacility(requestUtil.getInt("affiliatedFacilityID"),
                requestUtil.getInt("inspectionWellsNumber"),requestUtil.getInt("rainwaterOutletNumber"),
                requestUtil.getInt("streetSignNumber"),requestUtil.getDouble("treePondArea"),
                requestUtil.getString("other"),requestUtil.getInt("roadID"));
        Mapper<RoadMapper> roadMapperMapper = new Mapper<>(RoadMapper.class);
        try {
            RoadMapper mapper = roadMapperMapper.getMapper();
            boolean result = mapper.updateOneAffiliatedFacility(affiliatedFacility);
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        } finally {
            roadMapperMapper.closeSession();
        }
    }

    private void updateDividerOneSide(RequestUtil requestUtil) {
        String[] properties = { "position", "length", "wideRange", "area", "type", "guardraillength",
                "guardrailheight","guardrailType"};
        try (SqlSession sqlSession = Mapper.getSqlSession()) {
            RoadMapper mapper = sqlSession.getMapper(RoadMapper.class);
            boolean flag = true;
            for (int i = 0; i < requestUtil.getInt("Number"); i++) {
                boolean sqlResult = mapper.updateOneDividerOneSide(new DividerOneSide(
                        requestUtil.getInt("roadID"), requestUtil.getInt(properties[0] + i),
                        requestUtil.getDouble(properties[1] + i), requestUtil.getString(properties[2] + i),
                        requestUtil.getDouble(properties[3] + i), requestUtil.getString(properties[4] + i),
                        requestUtil.getDouble(properties[5] + i), requestUtil.getDouble(properties[6] + i),
                        requestUtil.getString(properties[7] + i)));
                if (!sqlResult) {
                    flag = false;
                    requestUtil.responseWrite("{\"result\": false + }");
                    sqlSession.rollback();
                    break;
                }
            }
            if (flag) {
                sqlSession.commit();
                requestUtil.responseWrite("{\"result\":" + true + "}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        }

    }


    private void updateSidewalkOneSide(RequestUtil requestUtil) {
        String[] properties = { "position", "pavementType", "length", "wideRange", "linearArea", "intersectionArea",
                "blindTrackLength","accessibleArea","greenbeltArea","sideStoneType","flatStoneType"};
        try (SqlSession sqlSession = Mapper.getSqlSession()) {
            RoadMapper mapper = sqlSession.getMapper(RoadMapper.class);
            boolean flag = true;
            for (int i = 0; i < requestUtil.getInt("Number"); i++) {
                boolean sqlResult = mapper.updateOneSidewalkOneSide(new SidewalkOneSide(
                        requestUtil.getInt("roadID"), requestUtil.getInt(properties[0] + i),
                        requestUtil.getString(properties[1] + i), requestUtil.getDouble(properties[2] + i),
                        requestUtil.getString(properties[3] + i), requestUtil.getDouble(properties[4] + i),
                        requestUtil.getDouble(properties[5] + i), requestUtil.getDouble(properties[6] + i),
                        requestUtil.getDouble(properties[7] + i), requestUtil.getDouble(properties[8] + i),
                        requestUtil.getString(properties[9] + i), requestUtil.getString(properties[10] + i)));
                if (!sqlResult) {
                    flag = false;
                    requestUtil.responseWrite("{\"result\": false + }");
                    sqlSession.rollback();
                    break;
                }
            }
            if (flag) {
                sqlSession.commit();
                requestUtil.responseWrite("{\"result\":" + true + "}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        }
    }

    private void updateAudit(RequestUtil requestUtil) {
        RoadAudit roadAudit = new RoadAudit(requestUtil.getInt("roadAuditID"), requestUtil.getInt("roadID"),
                requestUtil.getInt("departmentID"), requestUtil.getInt("auditStatus"));
        Mapper<RoadAuditMapper> roadAuditMapperMapper = new Mapper<>(RoadAuditMapper.class);
        try {
            RoadAuditMapper mapper = roadAuditMapperMapper.getMapper();
            boolean result = mapper.updateOneById(roadAudit);
            requestUtil.responseWrite("{\"result\":" + result + "}");
        } catch (Exception e) {
            e.printStackTrace();
            requestUtil.responseWrite("{\"result\": false + }");
        } finally {
            roadAuditMapperMapper.closeSession();
        }
    }
}
